/*
 * Drunk Js
 * Author    :   Drunk
 * Website   :   http://drunkce.com,  http://idrunk.net
 */


void function(){
window.variable = function(ele,type,config){
	return new variable.prototype.init(ele,type,config) ;
}

Drunk.control.cache.valiconPath = ownPath().dir;
$.extend(variable.prototype, {
	init : function(ele,type,config){
		var me = this ,
			elem = $(ele) ,
			attr = String(elem.attr('drunk')) ;

		me.elemWrap = $('<span>').insertAfter(elem).append(elem) ;
		me.elemName = elem.attr("name") ;

		me.config = Drunk.objParse(D.ifempty(config,'').spechar(17)) || {} ;
		me.type = type || '42' ;
		me.value = elem.val() ;
		me.attrs = elem.removeClass('vararea').attr('drunk', 'validate='+attr.replace(/^[^,]+?,'(\s*?|[^}]+?\})',/, '')).attrClone(0, 5) ;
		elem.removeAttr('drunk') ;
		me.build() ;
		return me ;
	} ,
	build : function(){
		var me = this ;
		me.elemWrap.empty() ;
		variable.data[me.type].build(me) ;
		if(typeof DC !== 'undefined' && Drunk.isFunc(DC))DC.init(me.elemWrap) ;
	} ,
	editor : function(type){
		var me = this ,
			table = '<table class="var_type">'+ variable.data[type].config +
				'<tr><th></th><td>' +
				'<input type="button" class="button" value="确定" />' +
				'</td></tr></table>' ;

		me.type = type ;
		me.elemWrap.empty().html(table).find('[name]').each(function(i, e){
			var elem = $(e) ,
				ename = elem.attr('name') ,
				value = elem.val() ;
			
			if(D.isUndef(me.config[ename]))return ;
			// 对单多行文本直接赋值
			if(elem.is('[type=text]') || elem.is('textarea')){
				elem.val(me.config[ename]) ;
			// 对单多选判断选中
			}else if(elem.is('[type=checkbox]') || elem.is('[type=radio]')){
				if(me.config[ename] = value)elem.prop('checked', true) ;
			}
		}) ;
		if(Drunk && Drunk.control && typeof Drunk.control.init === 'function')Drunk.control.init(me.elemWrap) ;
		me.elemWrap.find("table input[type=button]:last").bind("click", {'obj' : me}, variable.saveBuild) ;
		// 切换类型未保存前先清空
		if(me.configElem)me.configElem.val('') ;
	}
}) ;

variable.prototype.init.prototype = variable.prototype ;

$.extend(variable, {
    keditors : [],
	selectSeparated : '|||' ,
	pagingConfigSeparator : '[||||PCS|||]' ,
	// 保存配置并重建编辑器
	saveBuild : function(evt){
		var me = evt.data.obj ,
			elems = me.elemWrap.find('[name]') ,
			config = {} ,
			elem , tname ,type ,
			names = [] ,
			i = 0 ;

		elems.each(function(i, e){
			elem = $(e) ;
			tagName = elem.attr('tagName') ,
			type = elem.attr('type') || tagName ,
			names[names.length] = [elem.attr('name'), type] ;
		}) ;
		names = names.unique(0) ;

		for(;i<names.length;i++){
			tname = names[i][0] ;
			value = names[i][1] == 'radio' || names[i][1] == 'checkbox' ? me.elemWrap.find('[name='+tname+']:checked').val() : (
				names[i][1] == 'select' ? me.elemWrap.find('[name='+tname+']:selected').val() : me.elemWrap.find('[name='+tname+']').val()) ;
			tname = tname === 'ttype' ? 'type' : tname ;
			config[tname] = value === undefined ? '' : value ;
		}

		if(!me.configElem)me.configElem = $('<input>', {'type' : 'hidden', 'name' : 'config'}).insertAfter(me.elemWrap) ;
		// 保存配置
		me.config = config ;
		me.configElem.val(Drunk.dump(config)) ;
		me.build() ;
	}
}) ;

// {w:width, h:height, ipw:ispassword, im:ismulti, df:default, t:type, m:model, ip:ispaging, pl:paginglength, iap:isallowupload, ac:allowcount, as:allowsize, wp:watermarkposition, d:data, ii:isinterval, ic:intervalcount, 
// is:issingle, it:isthumb, at:allowtype, c:cate, ica:iscache, ml:minlength, r:root, l:level, s:struct, ws:withsecound, ts:timestamp, pua:pic_up_add, fua:fla_up_add, sua:swf_up_add, idp:is_del_org_pic, tc:thumb_config}
$.extend(variable, {
	data : {
		'42' : {
			'config' : '<tr><th>文本框长度：</th><td><input type="text" name="w" class="size" drunk="input=num" /> px</td></tr>' +
				'<tr><th>文本框高度：</th><td><input type="text" name="h" class="size" drunk="input=num" /> px</td></tr>' +
				'<tr><th>是否密码输入框：</th><td><input type="checkbox" name="ipw" /></td></tr>' +
				'<tr><th>是否多行文本：</th><td><input type="checkbox" name="im" value="1" /></td></tr>' +
				'<tr><th>默认值：</th><td><input type="text" name="df" /></td></tr>' ,
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config ,
					value = D.ifempty(me.value, D.ifempty(c['df'], '')),
                    elem;

				if(c.im){
                    elem = $("<textarea>", {'width':D.ifempty(c.w,'80%'), 'height':D.ifempty(c.h,'60'), 'text':value, 'name':vname}).attrClone(me.attrs).appendTo(me.elemWrap) ;
				}else{
                    elem = $("<input>", {'type':c.ipw ? 'password' : 'text', 'width':D.ifempty(c.w, '80%'), 'value':value, 'name':vname}).attrClone(me.attrs).appendTo(me.elemWrap) ;
				}
                variable.changeCall(elem, c);
                return elem;
			}
		} ,
		'43' : {
			'config' : '<tr><th>编辑器宽度：</th><td><input type="text" name="w" class="size" drunk="input=num" /> px</td></tr>' +
				'<tr><th>编辑器高度：</th><td><input type="text" name="h" class="size" drunk="input=num" /> px</td></tr>' +
				'<tr><th>编辑器模式：</th><td><label><input type="radio" name="m" value="0" checked />标准型</label> <label><input type="radio" name="m" value="1" />简洁型</label></td></tr>' +
				'<tr><th>是否内容分页：</th><td><label><input type="checkbox" name="ip" value="1" /></label></td></tr>' +
				'<tr><th>分页标题截取长度：</th><td><input type="text" name="pl" drunk="input=num" /></td></tr>' +
				'<tr><th>是否允许上传：</th><td><label><input type="checkbox" name="iap" value="1" checked /></label></td></tr>' +
				'<tr><th>图片上传地址：</th><td><input type="text" name="pua" value="" /></td></tr>' +
				'<tr><th>文件上传地址：</th><td><input type="text" name="fua" value="" /></td></tr>' +
				'<tr><th>FLASH上传地址：</th><td><input type="text" name="sua" value="" /></td></tr>' +
				'<tr><th>允许上传数：</th><td><input type="text" name="ac" class="size" drunk="input=num" value="20" /></td></tr>' +
				'<tr><th>上传文件大小：</th><td><input type="text" name="as" class="size" value="1" /> MB</td></tr>' +
				'<tr><th>水印位置：</th><td><label><input type="radio" name="wp" value="1" checked />不加水印</label>'+
					' <label><input type="radio" name="wp" value="1" />左上</label> <label><input type="radio" name="wp" value="2" />右上</label>'+
					' <label><input type="radio" name="wp" value="3" />左下</label> <label><input type="radio" name="wp" value="4" />右下</label><td></tr>' +
				'<tr><th>默认值：</th><td><textarea name="df"></textarea></td></tr>' ,
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config ,
					value = D.ifempty(me.value, D.ifempty(c['df'], '')) ,
					textarea , config = {} ,
					uploadTpl = '/index.php?s=/!menu_id.html' ,
					// 如果有配置pua,则如果pua为数字,则替补,否则直接使用
					uploadLink = D.empty(c.pua) ? null : (D.isInt(c.pua) ? uploadTpl.replace(/!menu_id/, c.pua) : c.pua) ;

				config.uploadJson = uploadLink ;
				if(!D.empty(c.cm)){
					config.designMode = false;
					config.items = ['fullscreen'];
				}
				if(!D.empty(c.fm))config.filterMode = false;
				if(!D.empty(c.tp))value = value.replace(/\[(__(?:TMPL|ROOT|APP|GROUP|ACTION|ACTION|SELF|URL|PUBLIC)__|\.{1,2}\/Pub(?:lic|oot))\]/gi, function($0,$1){return /\/pub/.test($1) ? $1.replace(/pub/,'Pub') : $1.toUpperCase();});
				textarea = $("<textarea>", {'width' : D.ifempty(c.w,'99%'), 'height' : D.ifempty(c.h,'400'), "text" : value, 'name':vname}).appendTo(me.elemWrap)
				// 判断是否启动文章分页,如果启动,则记录分页标题自动截取数
				if(D.ifempty(c.ip,''))config.paginglength = D.ifempty(c.pl,16) ;

				if(D.int(c.m))config.items = ['fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright',
					'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'image', 'link'] ;
				if(!D.ifempty(c.iap,0)){
					config.allowImageUpload = false ;
				}else{
					config.allowCount = D.ifempty(c.ac,20) ;
					config.allowSize = D.ifempty(c.as,1) ;
				}
				
				return variable.KECall(textarea, config) ;
			}
		},
		'44' : {
			'config' : '<tr><th>类型：</th><td><label><input type="radio" name="t" value="r" checked />单选框</label> ' +
				'<label><input type="radio" name="t" value="c" />多选框</label ><label><input type="radio" name="t" value="s" />下拉列表</label></td></tr>' +
				'<tr><th>选值：</th><td><textarea name="d"></textarea> value值与显示值之间用 '+variable.selectSeparated+' 隔开，多项以换行分隔！</td></tr>' +
				'<tr><th>默认值：</th><td><input type="text" name="df" /></td></tr>' ,
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config ,
					type = c.t ,
					value = me.value == '' ? D.ifempty(c.df, '') : me.value ,
					selectdataParse = variable.selectdataParse(D.ifempty(c.d,'')) ,
					selectedParse = variable.selectedParse(value) ,
					attribute ,i = 0 , label , input ;

				if(type == 's'){
					var selecter = $("<select>", {"name" : vname}).attrClone(me.attrs).appendTo(me.elemWrap) ;
					for(;i<selectdataParse.length;i++){
						attribute = {'value':selectdataParse[i][0], 'text' : selectdataParse[i][1]} ;
						if(selectedParse.search(selectdataParse[i][0]) != -1)attribute['selected'] = 'selected' ;
						$('<option>', attribute).appendTo(selecter) ;
					}
					return selecter ;
				}


				var hidden = $('<input>', {'type':'hidden', 'name':vname}).appendTo(me.elemWrap) ;
                // variable.changeCall(hidden, c);
				if(me.attrs.disabled)hidden.prop('disabled', true) ;
				hidden[0].elems = [] ;
				for(;i<selectdataParse.length;i++){
					attribute = {'name':'__'+vname+'__','value':selectdataParse[i][0], 'type' : type == 'r' ? 'radio' : 'checkbox'} ;
					if(selectedParse.search(selectdataParse[i][0]) != -1)attribute['checked'] = 'checked' ;
					input = $('<input>', attribute).attrClone(me.attrs) ;
					hidden[0].elems[hidden[0].elems.length] = input;
					label = $('<label>', {"text" : selectdataParse[i][1]}).prepend(input).appendTo(me.elemWrap) ;
					input.bind('change', {c:c}, function(evt){
						var x = 0 ,value_array = [] ;
						for(;x<hidden[0].elems.length;x++){
							if(!hidden[0].elems[x].is(':checked'))continue ;
							value_array[value_array.length] = hidden[0].elems[x].val() ;
						}
						hidden.val(value_array.join(',')) ;
                        if($.isFunction(evt.data.c.changeCall)) evt.data.c.changeCall.call(this, evt);
					}).trigger('change') ;
				}
			}
		},
		'45' : {
			'config' : '<tr><th>类型：</th><td><label><input type="radio" name="t" value="3" checked />日期时间</label> ' +
				'<label><input type="radio" name="t" value="1" />日期</label > <label><input type="radio" name="t" value="4" checked />月份</label> ' +
                '<label><input type="radio" name="t" value="2" />时间</label></td></tr>' +
				'<tr><th>文本框宽度：</th><td><input type="text" name="w" class="size" drunk="input=num" value="160" /> px</td></tr>' +
				'<tr><th>时间戳：</th><td><label><input type="checkbox" name="ts" value="1" checked /></label></td></tr>' +			
				'<tr><th>是否带秒：</th><td><label><input type="checkbox" name="ws" value="1" /></label></td></tr>' +			
				'<tr><th>是否区间：</th><td><label><input type="checkbox" name="ii" value="1" /></label></td></tr>' +			
				'<tr><th>区间数：</th><td><input type="text" name="ic" class="size" drunk="input=num" value="1" /></td></tr>' ,
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config , phpformat,
					config = {dateFormat:"yy-mm-dd",timeFormat:"HH:mm:ss",changeYear:true,changeMonth:true,showButtonPanel:true,altFieldTimeOnly:false} ,
					value , input , elem , ele,
                    timezoneOffset = new Date().getTimezoneOffset() * 60;

                if(me.value) me.value = me.value.trim();
                c.ts = !D.empty(c.ts);
				if($.isFunction(c.onselect)) config.onSelect = c.onselect;
                if(c.mindate) config.minDate = c.mindate;
                if(c.maxdate) config.maxDate = c.maxdate;
				// 单日期选择
				if(D.empty(c.ii)){
					if(c.ws)config.showSecond = true ;
					input = $('<input>', {'type':'hidden', 'name':vname, 'value':me.value}).appendTo(me.elemWrap) ;
					elem = $("<input>", {"type":"text", 'width':D.ifempty(c.w,'80')}).appendTo(me.elemWrap).attrClone(me.attrs);
					// 区块显示
					if(c.container){
						config.altField = elem;
						elem = $(c.container);
					}
                    // if(c.ts && (c.t == 2 || !D.empty(me.value))) me.value -= timezoneOffset;
					if(c.t == '1'){ // 日期
                        config.yearRange = 'c-80:c+20';
						elem.datepicker(config);
						if(!D.date_empty(me.value)) elem.datepicker('setDate', c.ts ? D.date('Y-m-d', me.value) : me.value) ;
					}else if(c.t == '2'){ // 时间
                        config.timeFormat = c.ws ? 'HH:mm:ss' : 'HH:mm';
                        elem.timepicker(config);
                        var regexp = c.ws ? /^\d+-\d+-\d+\s+/g : /^\d+-\d+-\d+\s+|:+\d+$/g;
                        if(me.value !== '') elem.timepicker('setTime', D.date('Y-m-d H:i:s', me.value).replace(regexp, '')) ;
                    }else if(c.t == '4'){ // 月份
                        elem.datepicker(D.extend(config, {
                            dateFormat : "yy-mm",
                            onChangeMonthYear : function(y, m){elem.datepicker('setDate', new Date(m +'/01'+'/'+ y)).trigger('change');},
                            onClose : function(ds, dt){elem.datepicker('setDate', new Date((dt.selectedMonth + 1) +'/01'+'/'+ dt.selectedYear)).trigger('change');}
                        }));
                        if(!D.date_empty(me.value)) elem.datepicker('setDate', new Date(c.ts ? D.date('Y-m-d', me.value) : me.value.replace(/(\d{4})\-(\d{2})/, '$2/01/$1')));
                    }else{ // 日期时间
                        config.timeFormat = c.ws ? 'HH:mm:ss' : 'HH:mm';
						elem.datetimepicker(config);
                        var valtext = c.ts ? D.date('Y-m-d H:i:s', me.value) : me.value;
                        if(!c.ws) valtext = valtext.replace(/:+\d+$/, '');
                        if(!D.date_empty(me.value)) elem.datetimepicker('setDate', valtext) ;
					}
                    elem.bind('focus', {is_month : c.t == '4'}, function(evt){
                        if(evt.data.is_month){
                            var e_this = $(this),
                                v_date = e_this.val();
                            e_this.datepicker('widget').addClass('month-picker');
                            if(v_date !== '') e_this.datepicker('setDate', new Date(v_date.replace(/(\d{4})\-(\d{2})/, '$2/01/$1')));
                        }else{
                            $(this).datepicker('widget').removeClass('month-picker');
                        }
                    });
					if(c.t != '2' && D.empty(me.value))elem.val('');
					return elem.bind('change', {c : c}, function(evt){
                        var c = evt.data.c;
                        var stamp = this.value == '' ? '' : Math.ceil(D.time((c.t == '2' ? '1970-1-1 ' : '') + this.value + ((c.t & 2) && !c.ws ? ':00' : '')));
                        input.val(c.ts && stamp !== '' ? stamp/* + timezoneOffset*/ : this.value);
                        if($.isFunction(c.changeCall)) c.changeCall.call(this, evt);
                    });
				}

				// 日期区间选择
				var from, to, fromName, toName, nbsp ,i = 0 ;
				for(;i<D.ifempty(c.ic,1);i++){
					nbsp = i >= D.ifempty(c.ic,'') -1 ? '' : '&nbsp;，' ;
					from = $("<input>", {"type":"text", 'width':D.ifempty(c.w,'80'), 'name':vname + '['+i+'][from]'}).appendTo(me.elemWrap).after('至').datepicker({'changeMonth':true,'changeYear':true}) ,
					to = $("<input>", {"type":"text", 'width':D.ifempty(c.w,'80'), 'name':vname + '['+i+'][to]'}).appendTo(me.elemWrap).after(nbsp).datepicker({'changeMonth':true,'changeYear':true}) ;
					from.datepicker('option', 'to' , to).datepicker('option', 'onClose', function(selectedDate , obj){obj.settings.to.datepicker('option', 'minDate', selectedDate);}) ;
					to.datepicker('option', 'from' , from).datepicker('option', 'onClose', function(selectedDate , obj){obj.settings.from.datepicker('option', 'maxDate', selectedDate);}) ;
				}
			}
		} ,
		'46' : {
			'config' : 	'<tr><th>图片上传地址：</th><td><input type="text" name="pua" value="" /></td></tr>' +
				'<tr><th>是否单张图片：</th><td><label><input type="checkbox" name="is" value="1" checked /></label></td></tr>' +
				'<tr><th>上传文件大小：</th><td><input type="text" name="as" class="size" value="1" /> MB</td></tr>' +
				'<tr><th>最大上传数：</th><td><input type="text" name="ac" class="size" drunk="input=num" value="20" /></td></tr>' +
				'<tr><th>水印位置：</th><td><label><input type="radio" name="wp" value="0" checked />不加水印</label>'+
					' <label><input type="radio" name="wp" value="1" />左上</label> <label><input type="radio" name="wp" value="2" />右上</label>'+
					' <label><input type="radio" name="wp" value="3" />左下</label> <label><input type="radio" name="wp" value="4" />右下</label><td></tr>' +
				'<tr><th>是否删除原图：</th><td><label><input type="checkbox" name="idp" value="1" /></label></td></tr>' +
				'<tr><th>是否缩放图片：</th><td><label><input type="checkbox" name="it" value="1" /></label></td></tr>' +
				'<tr><th>缩放配置：</th><td><input name="tc" value="" style="width:400px;" /></td></tr>' +
				'<tr><th></th><td>配置格式｛中文注释：缩略宽度,缩略高度,缩略方式,水印位置,等比例水印;实际值示例：300,300,0/1,1/2/3/4,0/1}，多个配置表示多个缩放，每个缩放之间用分号;隔开。第一个值表示缩放宽度，第二个表示缩放高度，如果宽或高为空则不缩放，'+
					'第三个值表示缩放方式（0：等比例铺满，1：等比例全图），第四个值表示水印位置（1：左上，2：左下，3：右上，4：右下），留空或其他则不加水印，第五个值表示是否不按比例缩放水印，默认会按比例缩放水印，如果配置为图片路径，'+
					'则使用该图片作为水印图片，请使用绝对路径。各个值之间以逗号,隔开，值本身不能带有逗号，不然会造成干扰。</td></tr>' ,
			'build' : function(me){
				// 单图上传
				if(me.config.is){  
                                    var reg = /^\{.*\}$/;
                                    var list = '<table class="new-up-one">';
                                        list += '<thead><td>文件名</td><td class="up-td">操作</td></thead>';
                                        list += '<tbody><tr><td><a class="link-hover" target="_blank" href="'+((me.value.length>0)?(reg.test(me.value)?eval('('+me.value+')').url:me.value):'')+'">'+((me.value.length>0)?(reg.test(me.value)?eval('('+me.value+')').title:me.value):'')+'</a></td><td class="up-btn"><em style="margin-right: 5px;">|</em><em class="del-btn">删除</em></td></tr></tbody>';
                                    list += '</table>';
                                    var no_sub = $(list).appendTo(me.elemWrap);
				var vname = me.elemName ,
					c = me.config ,
//                    cbtn = 'button-' + new Date().getTime().toString() + Math.random().toString().replace(/[^\d]/, ''),
//					button = $('<div>', {'class':'button', 'data-label':'上传'}).appendTo(me.elemWrap) ,
					button = $('<em>', {'class':'button', 'data-label':'上传'}).prependTo(no_sub.find('.up-btn')) ,
					// button = $('<input>', {'type':'button', 'class':'button', 'value':'上传'}).appendTo(me.elemWrap) ,
					elem = $('<input>', {type:'hidden', 'name':vname, value:me.value}).insertAfter(button) ,
					config = {}, dcm ,
					multiconf = $.isPlainObject(c.multi) ? c.multi : {},
					uploadTpl = '/index.php?s=/!menu_id.html' ,
					// 如果有配置pua,则如果pua为数字,则替补,否则直接使用
					uploadLink = D.empty(c.pua) ? null : (D.isInt(c.pua) ? uploadTpl.replace(/!menu_id/, c.pua) : c.pua) ;

				config.allowSize = D.ifempty(c.as,1) ;
				config.uploadJson = uploadLink ;
				config.isSingle = c.is ;
                                    
                                    no_sub.find('.del-btn').click(function(){   //删除操作
                                        var o_tr = $(this).closest('tr');
                                        o_tr.find('td:first').text('');
                                        o_tr.find('[name='+vname+']').val('');
                                    });

					multiconf.bachelor = true ;
//                                        console.log(1,button,2,c);
					if(!uploadLink)return ;
					// return variable.KECall(button, config, 'image', function(data){ console.log(data); dcm.add(data); }) ;
				// 多图上传
				}else{
                                    var regmore = /^\[\{.*\}\]$/;
                                    var list = '<table class="new-up-more">';
                                        list += '<thead><td>文件名</td><td class="up-more"></td></thead>';                                        
                                        if(me.value.length>0&&regmore.test(me.value)){
                                            list += '<tbody>';
                                            $.each(eval('('+me.value+')'),function(i,n){
                                                list += '<tr>';
                                                    list += '<td><a class="link-hover" target="_blank" href="'+n.url+'">'+(n.title?n.title:n.url)+'</a></td>';
                                                    list += '<td class="del-box"><em class="del-btn">删除</em></td>';
                                                list += '</tr>';
                                            });
                                            list += '</tbody>';
                                        }else{
                                            list += '<tbody>';
                                                list += '<tr><td>'+me.value+'</td><td class="del-box"><em class="del-btn">删除</em></td></tr>';
                                            list += '</tbody>';
                                        }
                                        list += '</table>';
                             
                                    var no_sub = $(list).appendTo(me.elemWrap);

				var vname = me.elemName ,
					c = me.config ,
//                    cbtn = 'button-' + new Date().getTime().toString() + Math.random().toString().replace(/[^\d]/, ''),
					button = $('<em>', {'class':'button', 'data-label':'上传'}).prependTo(no_sub.find('.up-more')) ,
					// button = $('<input>', {'type':'button', 'class':'button', 'value':'上传'}).appendTo(me.elemWrap) ,
					elem = $('<input>', {type:'hidden', 'name':vname, value:me.value}).insertAfter(button) ,
					config = {}, dcm ,
					multiconf = $.isPlainObject(c.multi) ? c.multi : {},
					uploadTpl = '/index.php?s=/!menu_id.html' ,
					// 如果有配置pua,则如果pua为数字,则替补,否则直接使用
					uploadLink = D.empty(c.pua) ? null : (D.isInt(c.pua) ? uploadTpl.replace(/!menu_id/, c.pua) : c.pua) ;

				config.allowSize = D.ifempty(c.as,1) ;
				config.uploadJson = uploadLink ;
				config.isSingle = c.is ;
                                
                                var up_mv = ((me.value.length>0&&regmore.test(me.value))?eval('('+me.value+')'):''); 
                                no_sub.on('click','.del-btn',function(){   //删除操作
                                    var o_tr = $(this).closest('tr'),
                                    i_tr = o_tr.index(),
                                    i_sib = o_tr.siblings('tr');
//                                        console.log(i_sib);
                                    if(i_sib.length>0){ //一个以上
                                        o_tr.remove();
                                        up_mv.splice(i_tr,1);
                                        up_mv = up_mv.sort();   //重新排序
                                        no_sub.find('[name='+vname+']').val(D.dump(up_mv));                                            
                                    }else{  //只剩一个
                                        o_tr.find('td:first').text('');
                                        if(up_mv.length){
                                            up_mv.splice(i_tr,1);
                                            up_mv = up_mv.sort();   //重新排序
                                        }
                                        
                                        no_sub.find('[name='+vname+']').val('');
                                    }
                                });
                                    
                                    
					multiconf.countLimit = config.ac ;
//                    if(!c.nomulti) dcm = Drunk.control.multi(elem, multiconf) ;
					if(!uploadLink)return ;
					config.allowCount = D.ifempty(c.ac,20) ;
                    /*return variable.KECall(button, config, 'multiimage', function(images){
                        for(var i=0; i<images.length; i++) images[i] = {title:images[i].title || '', url:images[i].url || ''};
                        dcm.add(images);
                    }) ;*/
				}
                return variable.webuploader(button, config, function(data){
                    if(c.is){   //单个上传 
                        if(Drunk.empty(data))return false ;       
                        elem.val(D.dump(data)).closest('tr').find('td:first').html('<a class="link-hover" target="_blank" href="'+data.url+'">'+data.title+'</a>');
                    }else{  
                        setTimeout(function(){
                            if(Drunk.empty(data))return false ; 
                            if($.trim(no_sub.find('[name='+vname+']').val())){
                                var ad_tr = '<tr><td><a class="link-hover" target="_blank" href="'+data.url+'">'+(data.title?data.title:data.url)+'</a></td><td class="del-box"><em class="del-btn">删除</em></td></tr>';
                                no_sub.append(ad_tr);
                            }else{
                                no_sub.find('tbody tr:first').find('td:first').html('<a class="link-hover"  target="_blank" href="'+data.url+'">'+data.title+'</a>');
                            }
                            if(up_mv.length){
                                up_mv.push(data);
                            }else{
                                up_mv = new Array();
                                up_mv.push(data);
                            }
                            no_sub.find('[name='+vname+']').val(D.dump(up_mv));
                        },1000);
//                        if(!c.nomulti) dcm.add(data);
                    }                    
                    if($.isFunction(c.afterupload)) c.afterupload.call(this, data);
                });
			}
		},
		'47' : {
			'config' : '<tr><th>文件上传地址：</th><td><input type="text" name="fua" value="" /></td></tr>' +
				'<tr><th>上传文件大小：</th><td><input type="text" name="as" class="size" drunk="input=num" value="1" /> MB</td></tr>' +
				'<tr><th>上传文件格式：</th><td><input type="text" name="at" value="rar,zip,7z,txt,swf,flv,mp3,wav,doc,docx,xls,xlsx,ppt,gz" /></td></tr>' ,
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config ,
					button = $('<input>', {'type':'button', 'class':'button', 'value':'上传'}).appendTo(me.elemWrap) ,
					elem = $('<input>', {'name':vname, value:me.value}).insertAfter(button) ,
					dcm = Drunk.control.multi(elem, {'bachelor' : true}) ,
					config = {} ;

				uploadTpl = '/index.php?s=/!menu_id.html' ,
				// 如果有配置pua,则如果pua为数字,则替补,否则直接使用
				uploadLink = D.empty(c.fua) ? null : (D.isInt(c.fua) ? uploadTpl.replace(/!menu_id/, c.fua) : c.fua) ;
				config.uploadJson = uploadLink ;
				config.allowSize = D.ifempty(c.as,1) ;

				return variable.KECall(button, config, 'insertfile', function(data){dcm.add(data);}) ;
			}
		},
		'48' : {
			'config' : '<tr><th>对象：</th><td><label><input type="radio" name="c" value="m" checked />会员ID</label> <label><input type="radio" name="c" value="p" />物业公司ID</label> '+
				'</label> <label><input type="radio" name="c" value="g" />物品</label> <label><input type="radio" name="c" value="gs" />物资</label> ' +
                '<label><input type="radio" name="c" value="b" />广告位</label></td></tr>'+
				'<tr><th>附加参数1：</th><td><input name="arg1" /></td></tr>'+
				'<tr><th>是否缓存：</th><td><input type="checkbox" name="ica" value="1" checked /></td></tr>'+
				'<tr><th>最小开始查询长度：</th><td><input type="text" name="ml" class="size" drunk="input=num" value="1" /></td></tr>'+
				'<tr><th>文本框宽度：</th><td><input type="text" name="w" class="size" drunk="input=num" value="80" /> px</td></tr>',
			'build' : function(me){
				var vname = me.elemName,
					c = me.config , para = '' , arg1, arg2, arg3;
				var input = $('<input>', {type:'hidden', 'name':vname}).appendTo(me.elemWrap).val(me.value),
					auto = $('<input>', {type:'text', 'width':D.ifempty(c.w, '80'), 'value':D.ifempty(c.text, '')}).appendTo(me.elemWrap).autocomplete().attrClone(me.attrs),
					cache = {},
					selecall = D.objParse(c.selecall),
					srcget = function(term){
						// 蛋疼的扩展,无赖又牛叉之举啊!扩展传递多动态参数.	(如果有定义参数,并且如果(如果参数为jquery对象,则覆盖参数为jquery值,否则保持不变,赋值)为真,则url追加)
						var para = [] ;
						para[para.length] = (!D.isUndef(c.arg1) && (arg1 = (c.jq_arg1 = $(c.arg1)) && c.jq_arg1.length ? c.jq_arg1.val() : c.arg1)) ? arg1 : '';
						para[para.length] = (!D.isUndef(c.arg2) && (arg2 = (c.jq_arg2 = $(c.arg2)) && c.jq_arg2.length ? c.jq_arg2.val() : c.arg2)) ? arg2 : '';
						para[para.length] = (!D.isUndef(c.arg3) && (arg3 = (c.jq_arg3 = $(c.arg3)) && c.jq_arg3.length ? c.jq_arg3.val() : c.arg3)) ? arg3 : '';
						return '/index.php?s=/79-'+D.ifempty(c.c, 'm')+'-'+para.join('-')+'-'+term+'-druson~1.html';
					};
                
				auto.bind('focus', function(){
                    var value = $(this).val();
                    if(value === '') $(this).autocomplete('search', value);
                }).bind('change',function(){
                    var value = $(this).val();
                    if(value === '') input.val(''); 
                }).bind('blur',function(){
                    setTimeout(function(){if(D.empty(input.val())){auto.val('');}},200);
                }).autocomplete({
					autoFocus : false,
					minLength: 0,
					source: function( request, response ){
						var term = request.term;
						if(term in cache){return response(cache[term]);}
						$.getJSON(srcget(term), function( data, status, xhr ) {
                            if(D.empty(data)){response('');input.val('');return;}
							var i = 0;
							if($.isArray(data))for( ;i<data.length;i++){data[i] = Drunk.objObj(data[i], ['value','label','property3','property4']);}
							if(c.ica)cache[term] = data;
                            if(!data.length){
                                input.val(request.term);
                            }else{
							    response(data);
                            }
						});
					} ,
					select : function(event, ui){
						auto.val(ui['item'].label);
						input.val(ui['item'].value);
						// 如果有选中回调
						if(D.isFunc(selecall))selecall(ui['item']);
						return false;
					}
//					,
//					focus: function( event, ui ) {
//						auto.val(ui['item'].label);
//						input.val(ui['item'].value);
//						return false;
//					}
				});
			}
		} ,
		'49' : {
			'config' : '<tr><th>对象：</th><td><label><input type="radio" name="c" value="c" checked />类别</label> <label><input type="radio" name="c" value="mn" />菜单' +
				'</label> <label><input type="radio" name="c" value="rl" />角色</label> <label><input type="radio" name="c" value="r" />地区</label></td></tr>' +
				'<tr><th>分类选择器类型：</th><td><label><input type="radio" name="t" value="s" checked />下拉列表</label> <label><input type="radio" name="t" value="r" />单选框</label> ' +
				'<label><input type="radio" name="t" value="c" />多选框</label></td></tr>' +
				'<tr><th>默认选值：</th><td><input type="text" name="df" class="size" /></td></tr>' +
				'<tr><th>结构元素名：</th><td><input type="text" name="s" class="size" drunk="input=num" /></td></tr>' +
				'<tr><th>根类：</th><td><input type="text" name="r" class="size" drunk="input=num" /></td></tr>' +
				'<tr><th>子级数：</th><td><input type="text" name="l" class="size" drunk="input=num" /></td></tr>' +
                '<tr><th>自定义配置：</th><td><textarea name="config"></textarea></td></tr>',
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config, elem,
                    urlpart = D.empty(c.config) ? '' : '-config~' + c.config.spechar(2);

				if(!D.empty(c.change) && !$.isFunction(c.change))try{eval("c.change="+c.change);}catch(e){c.change=0;} ;
                if(!D.isUndef(c.arg1)) urlpart += '-arg1~' + (((arg1 = (c.jq_arg1 = $(c.arg1)) && c.jq_arg1.length ? c.jq_arg1.val() : c.arg1)) ? arg1 : '');
                if(!D.isUndef(c.arg2)) urlpart += '-arg2~' + (((arg2 = (c.jq_arg2 = $(c.arg2)) && c.jq_arg2.length ? c.jq_arg2.val() : c.arg2)) ? arg2 : '');
                if(!D.isUndef(c.arg3)) urlpart += '-arg3~' + (((arg3 = (c.jq_arg3 = $(c.arg3)) && c.jq_arg3.length ? c.jq_arg3.val() : c.arg3)) ? arg3 : '');
				DCC(me.elemWrap, {
					rootId : D.ifempty(c.r, 1) ,
					topLevel : D.ifempty(c.l, 0) ,
					src : '/index.php?s=/78-!id-'+D.ifempty(c.c, 'c')+'-'+D.ifempty(c.l, 0)+'-druson~1'+urlpart+'.html' ,
					data : D.ifempty(c.d, []) ,
					defval : me.value ,
					deftext : c.df ,
					elemName : vname ,
					structName : c.s ,
					change : c.change
				}) ;
                elem = me.elemWrap.find('[name='+vname+']:hidden');
                elem.attrClone(me.attrs);
                variable.changeCall(elem, c);
			}
		},
		'50' : {
			'config' : '<tr><th>选值：</th><td><textarea name="d">1'+variable.selectSeparated+'审核\n64'+variable.selectSeparated+'隐藏\n32768'+variable.selectSeparated+'回收</textarea> value值与显示值之间用 '+variable.selectSeparated+' 隔开，多项以换行分隔！</td></tr>' +
				'<tr><th>默认值：</th><td><input type="text" name="df" value="1" /></td></tr>',
			'build' : function(me){
				var vname = me.elemName,
					c = me.config,
					value = D.ifempty(me.value, D.ifempty(c['df'], 0)),
					selectdataParse = variable.selectdataParse(D.ifempty(c.d,'')),
					selectedParse = variable.selectedParse(D.ifempty(value,'')),
					i = 0, elem,
					map = {1:'已审核',2:'已读',4:'已忽略',8:'已推荐至栏目',16:'已推荐至首页',32:'已置顶',64:'已隐藏',128:'已选中',256:'已标记',512:'已解决',1024:'已认证',2048:'已升级',4096:'已禁读',8192:'已锁定',16384:'已禁删',32768:'已回收'} ;

				for(;i<selectdataParse.length;i++){if(selectdataParse[i][0] == selectdataParse[i][1])selectdataParse[i][1] = map[selectdataParse[i][0]];}
				variable.statusControl(selectdataParse, vname, me.elemWrap, selectedParse, me);
                elem = me.elemWrap.find('[name='+vname+']:hidden');
                variable.changeCall(elem, c);
			}
		},
        '111' : {
            'config' : '<tr><th>根值：</th><td><input type="text" name="rootid" value="@mem.pid" /></td></tr>' +
                '<tr><th>表键：</th><td><input type="text" name="tabkey" value="meter" /></td></tr>' +
                '<tr><th>深度：</th><td><input type="text" name="deep" value="0" drunk="input=num" /></td></tr>' +
                '<tr><th>标签：</th><td><input type="checkbox" name="label" value="1" checked /></td></tr>',
            'build' : function(me){
                var vname = me.elemName,
                    c = me.config,
                    value = D.ifempty(me.value, 0),
                    urlpart = D.empty(c.config) ? '' : '-config~' + c.config.spechar(2);

                if(!D.isUndef(c.arg3)) urlpart += '-arg3~' + (((arg3 = (c.jq_arg3 = $(c.arg3)) && c.jq_arg3.length ? c.jq_arg3.val() : c.arg3)) ? arg3 : '');
                if(!c.data){
                    var url = '/index.php?s=/difflinkage-lg-' + c.tabkey +'-'+ c.rootid +'-'+ c.deep +urlpart+'.html';
                    $.get(url, function(data){linkage.init(me.elemWrap, data, value, c, vname);});
                }else{
                    try{
                        var data = $.parseJSON(c.data);
                    }catch(e){}
                    if(data) linkage.init(me.elemWrap, data, value, c, vname);
                }
            }
        },
		'verify' : {
			'build' : function(me){
				var vname = me.elemName ,
					c = me.config ;

				var input = $('<input>', {'name':vname}).attrClone(me.attrs).appendTo(me.elemWrap) ,
					src = '/index.php?s=/verify-'+vname+'-'+D.ifempty(c.c, 4)+'-'+D.ifempty(c.w, 80)+'-'+D.ifempty(c.h, 24)+'.html' ;
					input.bind('blur keyup keydown', function(){DC.code($(this), 4, this.value.length !== D.ifempty(c.c, 4) ? 1 : 4) ;}) ;
					img = $('<img>', {'src':src, 'style':'margin-left:10px;cursor:pointer;', title:'点击刷新验证码', alt:'验证码'}).insertAfter(input).bind('click', function(){this.src = src + '&_=' + Math.random() ;}) ;
			}
		}
	} ,

    changeCall : function(elem, c){
        if($.isFunction(c.changeCall)) elem.bind('change', {c:c}, c.changeCall);
    },

	// 默认选中值解析为数组
	selectedParse : function(data){return String(data).split(',') ;} ,

	// 将选值解析为数组
	selectdataParse : function(data){
		data = String(data) ;
		var matches = data.Match(/^(.+?)(\|\|\|(.+?))?$/gmi) ,
			i = 0, value, text, parseData = [] ;

		for(;i<matches.length;i++){
			if(!$.isArray(matches[i]) || !matches[i].length)continue ;
			value = matches[i][1] ;
			text = Drunk.isUndef(matches[i][3]) || !matches[i][3] ? value : matches[i][3] ;
			parseData[parseData.length] = [value, text] ;
		}
		
		return parseData ;
	} ,
	
	statusControl : function(data, elemName, wrap, status, obj){
		data = Drunk.empty(data) ? {} : data ;
		status = Drunk.bit(status, 1) ;

		var i = 0 , input , attribute, elems = $() ,
			elem = $('<input>', {'type':'hidden', 'name':elemName}).appendTo(wrap) ;

		delete obj.attrs.drunk ;
		for(;i<data.length;i++){
			if(!Drunk.bit(data[i][0], 16))continue ;
			attribute = {'type':'checkbox', 'value':data[i][0]} ;
			if((data[i][0] & status) == data[i][0])attribute['checked'] = 'checked' ;
			elems = elems.add($('<input>', attribute).attrClone(obj.attrs).prependTo($('<label>', {'text':data[i][1]}).appendTo(wrap))) ;
		}

		elems.bind('change', function(){
			var statuses = 0 ;
			elems.filter(':checked').each(function(i, e) {statuses = (statuses | Drunk.int(e.value))});
			elem.val(statuses) ;
		}).trigger('change') ;
		// 同步隐藏值的disabled属性
		if(obj.attrs.disabled)elem.prop('disabled', true) ;
	} ,

	// 调用KindEditor
	KECall : function(elem, config, plug, callback){
		if(typeof KindEditor === 'undefined')return alert(Math.random() > 0.6 ? 'Initialization failed ! The KindEditor is missing !' : '初始化失败！缺少KindEditor！') ;

		var editor, plugFunc = {'image':'imageDialog', 'multiimage':'multiImageDialog', 'insertfile':'fileDialog'},
            singlemap = {image:1, insertfile:1};

		config = $.isPlainObject(config) ? config : {} ;
		if(config.allowSize)config.imageSizeLimit = config.allowSize + 'MB' ;
		if(config.allowCount)config.imageUploadLimit = + config.allowCount ;
		delete config.allowSize;
		delete config.allowCount;

		if(!plug){
			// 失去焦点时更新分页信息
			if(!D.empty(config.paginglength)){
				config.afterBlur = function(){variable.KEPageBreak(this);}
				elem[0].paginglength = config.paginglength ;
			}
            editor = KindEditor.create(elem[0], config) ;
            variable.keditors.push(editor);
			if(!D.empty(config.paginglength))variable.KEPageBreak(editor) ;
			return editor ;
		}

		editor = KindEditor.editor(config);
		elem.click(function() {
			editor.loadPlugin(plug, function(){
				editor.plugin[plugFunc[plug]]({clickFn : function(){
					if($.isFunction(callback)) callback(singlemap[plug] ? {'url':arguments[0], 'title':arguments[1]} : arguments[0]);
					editor.hideDialog();
				}});
			});
		});
		return true ;
	} ,

	// 内容分页
	KEPageBreak : function(editor){
		var textarea = editor.srcElement[0] ;
		// 如果没启动内容分页,或者未定义分页分隔符,则直接返回
		var textelem = $(textarea) ,
			content = editor.html() ,
			pagingname = textelem.attr('name') + 'paging' ,
			paging = $('[name='+pagingname+']') ,
			difference , i , title , index ;

		if(editor.pagebreakHtml){
			var spliter = content.split(editor.pagebreakHtml) ;
		}else{
			if(paging.length)return ;
			// 如果未初始化过分页数据
			paging = $('<input type="hiddden" name="'+pagingname+'" />').insertAfter(textelem) ;
			var dcm ,
				config = {
					character : {'title' : '标题'} ,	fields : {'title' : 2} ,
					controls : {"编辑":function(evt){Drunk.control.multi.edit(evt.data.obj, evt.data.listItem, evt.data.listItem[0].index);}}
				} ;

			dcm = Drunk.control.multi(paging, config) ;
			textarea.dcm = dcm ;
			textarea.paging = [] ;
			// 增加数据同步回调
			editor.syncall = function(html){
				var _textarea = this.srcElement[0] ;
				if(_textarea.paging && _textarea.paging.length)html = Drunk.dump(_textarea.paging) + variable.pagingConfigSeparator + html;
				return html ;
			}

			// 切割初始数据, 分离分页配置与主内容, \n 若无分页则直接返回
			var content_spliter = content.split(variable.pagingConfigSeparator) ;
			if(content_spliter.length < 2)return ;
			var items = D.objParse(content_spliter[0]) ,
				content = content_spliter[1] ;

			// 初始化分页编辑器数据, \n 初始化分页记录控件分页配置记录, \n 重载主内容并返回
			for(i=0;i<items.length;i++)textarea.dcm.add(items[i]) ;
			textarea.paging = items ;
			return editor.html(content) ;
		}

		difference = spliter.length - textarea.paging.length ;
		// 删除部分分页
		if(difference < 0){
			for(i=0; i<-difference; i++){
				index = textarea.dcm.items.length - 1 ;
				Drunk.control.multi.remove(textarea.dcm, textarea.dcm.root.find('tr:eq('+index+')'), index) ;
			}
			textarea.paging = textarea.dcm.items ;
		// 无删减,不需做任何操作
		}else if(!difference){return ;}

		// 增加
		for(i=textarea.paging.length; i< spliter.length; i++){
			title = spliter[i].striptags().trim(3, '\\s|&nbsp;').substr(0, textarea.paginglength) ;
			textarea.dcm.add(title) ;
			textarea.paging = textarea.dcm.items ;
		}
	},
    /**
     * 初始化webuploader
     * @param button
     * @param config {
     *   uploadJson : 上传地址,
     *   allowCount : 最大数量,
     *   isSingle : 是否单张
     *   accept : 指定接受哪些类型的文件 [同时存在]
     *   fileTypeExts : 指定接受哪些类型的文件 [同时存在]
     * }
     * @param callback
     */
    webuploader : function(button, config, callback){
        var ie_v = variable.ie_test(navigator.userAgent);
        if(ie_v&&ie_v<9){
            return variable.uploadify(button, config, callback);
        }        
        var jbutton = button.length ? button : $(button),
            clab = button.attr('data-label'),
            c = {
                swf: Drunk.local.pathdir + '../webuploader/Uploader.swf',
                server : config.uploadJson,
                auto : true,
                fileVal : 'webuploader',
                duplicate : true,
                chunked: true,
                pick : {
                    id : jbutton[0],
                    label : clab
                },
                compress : {
                    width: 1920,
                    height: 1080,
                    // 图片质量，只有type为`image/jpeg`的时候才有效。
                    quality: 90,
                    // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
                    allowMagnify: false,
                    // 是否允许裁剪。
                    crop: false,
                    // 是否保留头部meta信息。
                    preserveHeaders: true,
                    // 如果发现压缩后文件大小比原来还大，则使用原来图片
                    // 此属性可能会影响图片自动纠正功能
                    noCompressIfLarger: false,
                    // 单位字节，如果图片大小小于此值，不会采用压缩。
                    compressSize: 1024 * 256
                },
                onUploadSuccess : function(file, upfile){
                    if(!upfile || upfile.error) return false;
                    callback.call(this, {url : upfile.url, title : upfile.title}, file);
                }
            };
        if(config.allowCount) c.fileNumLimit = config.ac;
        if(config.isSingle) c.pick.multiple = false;
        if(config.accept) c.accept = config.accept;
        return new WebUploader.create(c);
    },
    ie_test : function(ua){
        var ret = {};
        var ie = ua.match( /MSIE\s([\d\.]+)/ ) || ua.match( /(?:trident)(?:.*rv:([\w.]+))?/i );
        ie && (ret.ie = parseFloat( ie[ 1 ] ));
        if($.trim(ie)){
            return parseFloat(ie[1]);
        }
        return null;
    },
    up_build_one : function(upbox,cnf){    //构建统一的HTML单文件上传格式 
        if($.isEmptyObject(upbox)||!upbox.length) return false;
        if(!cnf.uploadJson.length) return false;
        var c = {
            filename : 'file',  //表单域名称
            data : ''   ,//数据
            uploadJson : '' //上传链接
        };
        if(cnf.filename) c.filename = cnf.filename;
        if(cnf.data) c.data = cnf.data;
        if(cnf.uploadJson) c.uploadJson = cnf.uploadJson;
        var reg = /^\{.*\}$/;
        var list = '';
        list += '<span>';
            list += '<table class="new-up-one">';
                list += '<thead><tr><td>文件名</td><td class="up-td">操作</td></tr></thead>';
                list += '<tbody><tr>';
                    list += '<td><a class="link-hover" target="_blank" href="'+((c.data.length>0)?(reg.test(c.data)?eval('('+c.data+')').url:c.data):'')+'">'+((c.data.length>0)?(reg.test(c.data)?eval('('+c.data+')').title:c.data):'')+'</a></td>';
                    list += '<td class="up-btn"><em class="button" data-label="上传"></em><input type="hidden" name="'+c.filename+'" value=\''+c.data+'\'><em style="margin-right: 5px;">|</em><em class="del-btn">删除</em></td>';                    
                list += '</tbody>';
            list += '</tr></table>';
        list += '</span>';
        var elemnode = upbox.html($(list));
        elemnode.find('.del-btn').click(function(){   //删除操作
            var o_tr = $(this).closest('tr');
            o_tr.find('td:first').text('');
            o_tr.find('[name='+c.filename+']').val('');
        });
        //上传
        variable.webuploader(elemnode.find('.new-up-one .up-btn .button'), {
            uploadJson : c.uploadJson,
            isSingle : true
        }, function(data){
            if(Drunk.empty(data)) return false;
            elemnode.find('[name='+c.filename+']').val(D.dump(data)).closest('tr').find('td:first').html('<a class="link-hover" target="_blank" href="'+data.url+'">'+data.title+'</a>');
        });
    
    },
    uploadify : function(button, config, callback){
        var jbutton = button.length ? button : $(button),
            clab = button.attr('data-label'),
            c = {
                swf : Drunk.local.pathdir + '../uploadify/uploadify.swf',
                buttonText : clab,
                buttonImage : null,
                buttonClass : 'up-bt-class',
                width : 34,
                height : 17,
                uploader : config.uploadJson,
                auto : true,
                fileObjName : 'webuploader',    
                multi : true,
                preventCaching : true,
                onUploadSuccess : function(file, upfile,response){
                    upfile = upfile.length?eval('('+upfile+')'):{};
                    if(!upfile || upfile.error) return false;
                    callback.call(this, {url : upfile.url, title : upfile.title}, file);
                }

            };
        if(config.allowCount) c.uploadLimit = config.ac;
        if(config.isSingle){
            c.multi = false;
            c.width = 24;
        }
        if(config.fileTypeExts) c.fileTypeExts = config.fileTypeExts;
        if(config.width) c.width = config.width;
        if(config.height) c.height = config.height;
        var bt = $('<input>',{type:'file',id:'file_upload_'+Math.round(Math.random()*10000),name:'file_upload'}).prependTo(jbutton);
        return bt.uploadify(c);
    }
}) ;


var linkage = {
    // 初始化
    init : function(wrap, data, value, c, ename){
        if(!data.fields) return;
        var wrape = wrap[0], values;
        linkage.fieldPrefix(c, data);
        c.deep = D.int(c.deep) ? c.deep : data.fields.length;
        values = value ? ((values = linkage.datadeep(data.data, value, c.deep)) ? values : [0]) : [0];
        if(ename) data.fields[data.fields.length - 1][0] = ename; // 如果有传入表单元素名, 则用其做联动元素名
        wrape.c = {data : data.data, fields : data.fields, values : values, c : c, elems : {}};
        for(var i=0; i<values.length; i++) linkage.build(wrape, i);
        if($.isFunction(c.initCall)) c.initCall(wrap, value); // 值变回调
    },
    // 补前缀
    fieldPrefix : function(c, data){
        if(!c.prefix) return;
        for(var i=0; i<data.fields.length; i++){
            if(new RegExp('^'+c.prefix+'-').test(data.fields[i][0])) continue;
            data.fields[i][0] = c.prefix + '-' + data.fields[i][0];
        }
    },
    // 建立选择器
    build : function(e, i){
        var elem = $(e), data = e.c.data.slice(), idx, select,
            i = i === undefined ? e.c.values.length - 1 : i,
            selname = e.c.fields[i] ? e.c.fields[i][0] : '';

        for(var j=0; j<=i; j++){
            if(!j)continue;
            idx = data.search(e.c.values[j - 1], ['id']);
            data = idx === -1 || !data[idx].children ? [] : data[idx].children;
        }
        if(!e.c.elems[selname]){
            if(!data.length) return linkage.remove(e, i, 1);    // 仅弹数组
            var label = e.c.c.label ? e.c.fields[i][1]+'：' : '', eselect, selectchange,
                labelTag = '<label class="linkage" '+(D.int(e.c.c.deep) === i + 1 ? 'linkage-finally' : '')+'>' +label+ '</label>';
            selectchange = function(evt){
                var e = this.e;
                if($.isFunction(e.c.c.changeCall)) e.c.c.changeCall(this); // 值变回调
                for(var j=e.c.values.length; j--; j>0){if(j <= this.i) break;linkage.remove(e, j);}
                e.c.values.splice(e.c.values.length - 1, 1, this.value);
                if(!D.int(this.value)) return;
                e.c.values.push(0);
                linkage.build(e);
            };
            eselect = $('<select name="' +selname+ '">');
            e.c.elems[selname] = $(labelTag).append(eselect).appendTo(elem);
            e.c.elems[selname].children('select')[0].i = i;
            eselect[0].e = e;
            if(e.c.c.selectmenu){
                eselect.selectmenu({select : selectchange});
            }else{
                eselect.bind('change', selectchange)
            }
        }else{
            if(!data.length) return linkage.remove(e, i);
            e.c.elems[selname].children('select').empty();
        }
        select = e.c.elems[selname].children('select');
        select.append('<option value="">请选择</option>');
        for(var j=0;j<data.length;j++) $('<option value="' +data[j].id+ '" ' +(data[j].id == e.c.values[i] ? 'selected' : '')+ '>' +data[j]['name']+ '</option>').appendTo(select);
        if(e.c.c.selectmenu){
            select.selectmenu('refresh');
            if(e.c.values[i] && $.isFunction(e.c.c.changeCall)) e.c.c.changeCall(this); // 值变回调
        }
    },
    // 移除选择器
    remove : function(e, j, bit){
        e.c.values.pop();
        if(bit & 1) return;
        e.c.elems[e.c.fields[j][0]].remove();
        delete e.c.elems[e.c.fields[j][0]];
    },
    // 从递归数据找出子数据直属父关系队列
    datadeep : function(data, value, deep, level){
        if(!level) level = 1;
        var branch;
        for(var i=0;i<data.length;i++){
            if(deep && level >= deep){
                if(data[i].id == value) return [data[i].id];
            }else{
                if(!data[i].children) continue;
                if(undefined !== (branch = linkage.datadeep(data[i].children, value, deep, level + 1))) return [data[i].id].concat(branch);
            }
        }
        if(level >= deep) return undefined;
    }
};
}() ;